package com.jt.common.filter;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
//过滤器（特殊的拦截器）
interface Filter{
    boolean filter();
}
//控制器（负责请求分发）
interface Servlet{
    void dispatch();
}
//过滤链
class FilterChain{
    private List<Filter> filters = new CopyOnWriteArrayList<>();//过滤器（请求数据过滤）
    private Servlet servlet;//控制器（请求控制逻辑）

    public FilterChain(List<Filter> filters, Servlet servlet) {
        this.filters.addAll(filters);
        this.servlet = servlet;
    }

    public void doFilter(){//执行过滤链

        //先请求过滤
        for (int i = 0 ;i<filters.size();i++){
            if(!filters.get(i).filter()){
                return;
            };
        }
        servlet.dispatch();//请求分发
        for (int i = filters.size()-1 ;i>=0 ;i--){
            if(!filters.get(i).filter()){
                return;
            };
        }
        //


    }
}

public class FilterChainTests {
    public static void main(String[] args) {
        Filter filter1 = new Filter() {
            @Override
            public boolean filter() {
                System.out.println("filter 01");
                return true;
            }
        };
        Filter filter2 = new Filter() {
            @Override
            public boolean filter() {
                System.out.println("filter 02");
                return true;
            }
        };
        List<Filter> filters = new CopyOnWriteArrayList<>();
        filters.add(filter1);
        filters.add(filter2);
        //执行
        FilterChain filterChain = new FilterChain(filters, new Servlet() {
            @Override
            public void dispatch() {
                System.out.println("将请求分发给具体对象去执行");
            }
        });
        filterChain.doFilter();
    }
}
